package kr.or.eclipse.democamp.actions;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.eclipse.democamp.ActivateToken;
import kr.or.eclipse.democamp.Contact;
import kr.or.eclipse.democamp.PMF;

public class Activate extends Action {
	public Activate() {
		super("activate");
	}

	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) {
		String code = req.getParameter("code");
		PersistenceManager manager = PMF.get().getPersistenceManager();
		ActivateToken token = manager.getObjectById(ActivateToken.class, code);
		if (token != null) {
			Contact contact = manager.getObjectById(Contact.class, token.getMail());
			if (contact != null) {
				if (!contact.getMailConfirmed()) {
					contact.setMailConfirmed(true);
					manager.makePersistent(contact);
					try {
						resp.getWriter()
								.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><title>Eclipse Demo Camp in SEOUL</title><body>메일이 확인 되었습니다. 감사합니다.</body></html>");
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					try {
						resp.getWriter()
								.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><title>Eclipse Demo Camp in SEOUL</title><body>이미 메일이 확인 되었습니다. 감사합니다.</body></html>");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		manager.close();
	}

}
